<template>
  <div>
    <p style="font-size: 20px">{{ msg }}</p>
    <!-- 显示处理列表 -->
    <el-table :data="pagedTreat" style="width: 100%">
      <el-table-column prop="new_id" label="编号" width="80"/>
      <el-table-column prop="drug_name" label="药品名称"/>
      <el-table-column prop="drug_quantity" label="药品数量"/>
      <el-table-column prop="treatment_date" label="处理日期"/>
      <el-table-column prop="treatment_method" label="处理方法"/>
      <el-table-column prop="treatment_reseon" label="处理原因"/>
      <el-table-column prop="treated_by" label="处理人"/>
      <el-table-column align="right">
        <!--        delete与edit的实现-->
        <!--        Delete button -->
        <template #default="scope">
          <div style="display: flex;align-items: center;" v-if="haspermission(['admin','manager'])">
            <!-- Edit button with popover -->
            <el-button size="small" type="danger" @click="open_delete(scope.row)">Delete</el-button>
            <el-popover placement="right" :width="320" trigger="click">
              <template #reference>
                <el-button size="small" @click="setValue(scope.row)">Edit</el-button>
              </template>
              <div>
                <form @submit="handleEdit">
                  <p>向后端修改处理信息:</p>
                  <label>名称：</label>
                  <el-input
                      v-model="treatEdit.drug_name"
                      style="width: 240px"
                      show-word-limit
                      type=text
                  />
                  <label>数量：</label>
                  <el-input
                      v-model="treatEdit.drug_quantity"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type=number
                  />
                  <label>日期：</label>
                  <el-date-picker
                      v-model="treatEdit.treatment_date"
                      type="date"
                      placeholder="选择处理日期"
                      style="width: 240px">
                  </el-date-picker>
                  <label>方法：</label>
                  <el-input
                      v-model="treatEdit.treatment_method"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type="text"
                  /><label>原因：</label>
                  <el-input
                      v-model="treatEdit.treatment_reseon"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type="text"
                  /><label>员工：</label>
                  <el-input
                      v-model="treatEdit.treated_by"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type=text
                  />
                  <div style="margin: 20px 0"/>
                  <el-button type="info" round @click="handleEdit(scope.row)" size="small">提交修改</el-button>
                </form>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 30px"
        layout="prev, pager, next"
        :total="total"
        v-model="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
    />

    <div style="display: flex; align-items: center;">
      <!-- 添加处理的表单 -->
      <form @submit="drugSubmit" ref="addForm">
        <h3>向后端添加处理的表单:</h3>
        <el-input
            v-model="inputTreat.drug_name"
            style="width: 240px"
            maxlength="20"
            placeholder="药品名称"
            show-word-limit
            type=text
        />
        <div style="margin: 5px 0"/>
        <el-input
            v-model="inputTreat.drug_quantity"
            maxlength="20"
            style="width: 240px"
            placeholder="药品数量"
            show-word-limit
            type="number"
        />
        <div style="margin: 5px 0"/>
        <el-date-picker
            v-model="inputTreat.treatment_date"
            type="date"
            placeholder="选择处理日期"
            style="width: 240px">
        </el-date-picker>
        <div style="margin: 5px 0"/>
        <el-input
            v-model="inputTreat.treatment_method"
            maxlength="20"
            style="width: 240px"
            placeholder="方法"
            show-word-limit
            type=text
        />
        <div style="margin: 5px 0"/>
        <el-input
            v-model="inputTreat.treatment_reseon"
            maxlength="20"
            style="width: 240px"
            placeholder="原因"
            show-word-limit
            type=text
        />
        <div style="margin: 5px 0"/>
        <el-input
            v-model="inputTreat.treated_by"
            maxlength="20"
            style="width: 240px"
            placeholder="处理人"
            show-word-limit
            type=text
        />
        <hr>
        <el-button type="success" round @click="drugSubmit">提交</el-button>
      </form>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询处理的表单1</h3>
        <label>用户名称：</label>
        <el-input type="text" style="width: 240px" v-model="name"/>
        <div style="margin: 20px 0"/>
        <el-popover placement="right" :width="600" trigger="click">
          <template #reference>
            <el-button type="info" @click="findSolve">按处理人名称查找</el-button>
          </template>
          <el-table :data="ssolve">
            <el-table-column prop="new_id" label="编号" width="80"/>
            <el-table-column prop="drug_name" label="药品名称"/>
            <el-table-column prop="drug_quantity" label="药品数量"/>
            <el-table-column prop="treatment_date" label="处理日期"/>
            <el-table-column prop="treatment_method" label="处理方法"/>
            <el-table-column prop="treatment_reseon" label="处理原因"/>
            <el-table-column prop="treated_by" label="处理人"/>
          </el-table>
        </el-popover>
      </div>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询处理的表单2</h3>
        <label>处理日期：</label>
        <el-date-picker
            v-model="date"
            type="date"
            placeholder="选择处理日期"
            style="width: 240px">
        </el-date-picker>
        <div style="margin: 20px 0"/>
        <el-popover placement="right" :width="600" trigger="click">
          <template #reference>
            <el-button type="info" @click="findSolve2">按处理日期查找</el-button>
          </template>
          <el-table :data="ssolve">
            <el-table-column prop="new_id" label="编号" width="80"/>
            <el-table-column prop="drug_name" label="药品名称"/>
            <el-table-column prop="drug_quantity" label="药品数量"/>
            <el-table-column prop="treatment_date" label="处理日期"/>
            <el-table-column prop="treatment_method" label="处理方法"/>
            <el-table-column prop="treatment_reseon" label="处理原因"/>
            <el-table-column prop="treated_by" label="处理人"/>
          </el-table>
        </el-popover>
      </div>
      <div style="padding: 5%"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, h, onMounted, ref, watch} from 'vue';
import {
  getTreat,
  postTreat,
  deleteTreat,
  updateTreat,
  findByPeople,
  findByDate,
} from '@/api/api'
import {ElMessage, ElMessageBox} from "element-plus";
import {useLoginStore} from "@/stores";

const store = useLoginStore();

function haspermission(allowance: string[]) {
  return allowance.indexOf(store.role) !== -1;
}
const msg = ref('欢迎来到处理管理板块');
const inputTreat = ref({
  drug_name:"",
  drug_quantity:Number,
  treatment_date:new Date(),
  treatment_method:"",
  treatment_reseon:"",
  treated_by:""
});

//增
async function drugSubmit() {
  try {
    // drug_name, drug_quantity, treatment_date, treatment_method, treatment_reseon, treated_by
    inputTreat.value.treatment_date.setHours(inputTreat.value.treatment_date.getHours() + 8);

    let formattedDate: string;

    if (inputTreat.value && inputTreat.value.treatment_date) {
      // 使用 toLocaleString 方法将 Date 对象格式化为字符串
      const options: Intl.DateTimeFormatOptions = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      };
      formattedDate = inputTreat.value.treatment_date.toISOString().split('T')[0];
    } else {
      // 处理 inputTreat.value.treatment_date 不是 Date 对象的情况
      formattedDate = 'Invalid date'; // 或者其他适当的默认值
    }

    const response = await postTreat(inputTreat.value.drug_name,inputTreat.value.drug_quantity,formattedDate,
        inputTreat.value.treatment_method,inputTreat.value.treatment_reseon,inputTreat.value.treated_by);
    console.log(response);
    await loadTreats();
    // 清空输入字段
    inputTreat.value = {drug_name:"", drug_quantity:Number,treatment_date:new Date(), treatment_method:"",treatment_reseon: "",treated_by:""};
  } catch (error) {
    console.error('Error submitting treat:', error);
    // 在这里可以添加错误处理的逻辑
  }
}

//删
async function deleteTreatAndHandleResponse(id: number) {
  try {
    const response = await deleteTreat(id);
    console.log('Treat deleted successfully', response);
    await loadTreats()
  } catch (error) {
    console.error('Error deleting Treat', error);
  }
}

const open_delete = (obj: any) => {
  ElMessageBox({
    title: 'Message',
    message: h('p', null, [
      h('span', null, '请注意删除操作是不可逆的'),
      h('i', {style: 'color: teal'}, '数据库会同步变化'),
    ]),
    showCancelButton: true,
    confirmButtonText: '确认删除',
    cancelButtonText: '取消删除',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        deleteTreatAndHandleResponse(obj.id);
        // window.location.reload()
        done();
      } else {
        done();
      }
    },
  }).then((action) => {
    ElMessage({
      type: 'info',
      message: `操作结果: ${action === 'confirm' ? '删除成功' : '已取消删除'}`,
    });
  });
}

//改
const treatEdit = ref({
  drug_name:"",
  drug_quantity:Number,
  treatment_date:"",
  treatment_method:"",
  treatment_reseon:"",
  treated_by:""
})

function setValue(obj: any) {
  treatEdit.value.drug_name = obj.drug_name;
  treatEdit.value.drug_quantity = obj.drug_quantity;
  treatEdit.value.treatment_date = obj.treatment_date;
  treatEdit.value.treatment_method = obj.treatment_method;
  treatEdit.value.treatment_reseon = obj.treatment_reseon;
  treatEdit.value.treated_by = obj.treated_by;
}


async function handleEdit(obj: any) {
  try {
    const response = await updateTreat(obj.id, treatEdit.value)
    console.log("Treat edit successfully", response)
    await loadTreats()
    ElMessage({
      type: 'info',
      message: `操作结果:'修改成功'`,
    });
  } catch (error) {
    console.error(error);
  }
}

//查
const drugs = ref([
  {id: 1, drug_name:"", drug_quantity:Number, treatment_date:"", treatment_method:"",treatment_reseon: "",treated_by:"", new_id: 0},
  {id: 2, drug_name:"", drug_quantity:Number, treatment_date:"", treatment_method:"",treatment_reseon: "",treated_by:"", new_id: 0},
])
let currentPage = ref(1)
const pageSize = ref(6)
const total = ref(drugs.value.length) // 计算总记录数

watch(drugs, (newValue) => {
  total.value = newValue.length;
});
const pagedTreat = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;

  return drugs.value.slice(startIndex, endIndex);
});

function handlePageChange(newPage: number) {
  currentPage.value = newPage
}

async function loadTreats() {
  try {
    const response = await getTreat();
    // 假设 response.data 是一个处理数组
    drugs.value = response.data;
    let new_index = 1;
    for (let oneMoney of drugs.value) {
      oneMoney.new_id = new_index;
      new_index++;
    }
  } catch (error) {
    // 处理错误情况
    console.error('Error loading drugs:', error);
  }
}
onMounted(() => {
  loadTreats();
});

//特殊查寻
const date = ref(new Date());
const name = ref('')
const ssolve = ref([
  {id: 1, drug_name:"", drug_quantity:Number, treatment_date:"", treatment_method:"",treatment_reseon: "",treated_by:"", new_id: 0},
])

async function findSolve() {
  try {
    const response = await findByPeople(name.value);
    ssolve.value = response.data
    console.log(response)
    console.log(ssolve.value)
    let index = 1
    for (let i of ssolve.value) {
      i.new_id = index
      index++
    }
  } catch (error) {
    console.error("Error finding drug:", error);
  }
}

async function findSolve2() {
  try {
    date.value.setHours(date.value.getHours() + 8);
    let formattedDate: string;

    if (inputTreat.value && inputTreat.value.treatment_date) {
      // 使用 toLocaleString 方法将 Date 对象格式化为字符串
      const options: Intl.DateTimeFormatOptions = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      };
      formattedDate = date.value.toISOString().split('T')[0];
      console.log(formattedDate)
      console.log(date.value)
    } else {
      formattedDate = 'Invalid date'; // 或者其他适当的默认值
    }

    const response = await findByDate(formattedDate);
    ssolve.value = response.data
    console.log(response)
    console.log(ssolve.value)
    let index = 1
    for (let i of ssolve.value) {
      i.new_id = index
      index++
    }
  } catch (error) {
    console.error("Error finding drug:", error);
  }
}
</script>